﻿<script setup lang="ts">
import { putUserAPI } from '@/services/my'
import { putUserAutenticationSponsor, putUserAutenticationStudent } from '@/services/profile'
import { getSchoolListAPI } from '@/services/home'
import { useMemberStore } from '@/stores'
import { computed, ref, onMounted } from 'vue'
import type { School } from '@/types/home'

// 获取会员信息
const memberStore = useMemberStore()
const userProfile = computed(() => memberStore.profile?.user)

// 定义可修改的用户名，初始值为用户当前用户名
const editableName = ref(userProfile.value?.userName || '')

// 定义可修改的身份证号，初始值为用户当前身份证号
const editableIdCard = ref(userProfile.value?.idCard || '')
// 身份证验证错误信息
const idCardError = ref('')

// 控制认证选项显示状态
const showCertOptions = ref(false)

// 控制邀请码对话框显示状态
const showInviteDialog = ref(false)
// 邀请码输入值
const inviteCode = ref('')

// 控制学生认证对话框显示状态
const showStudentDialog = ref(false)
// 学生认证表单数据
const studentForm = ref({
  schoolId: '',
  studentId: '',
})
// 学校列表
const schoolList = ref<School[]>([])

// 计算当前用户的学校名称
const userSchoolName = computed(() => {
  if (!userProfile.value?.schoolId) return ''
  const schoolId = userProfile.value.schoolId
  const school = schoolList.value.find((s: School) => s.id === schoolId)
  return school?.schoolName || ''
})

// 获取学校列表
const getSchoolList = async () => {
  try {
    const res = await getSchoolListAPI()
    schoolList.value = res.rows
  } catch (error) {
    console.error('获取学校列表失败:', error)
    uni.showToast({
      title: '获取学校列表失败',
      icon: 'none',
    })
  }
}

// 计算认证类型
const certificationType = computed(() => {
  if (userProfile.value?.status === 1) {
    return userProfile.value?.inviteCode ? 'sponsor' : 'student'
  }
  return 'none'
})

// 处理认证状态点击
const handleStatusClick = () => {
  showCertOptions.value = !showCertOptions.value
}

// 跳转到认证页面
const goCertification = (type: string) => {
  if (type === '赞助商') {
    // 显示邀请码输入对话框
    showInviteDialog.value = true
  } else if (type === '学生') {
    // 显示学生认证对话框
    showStudentDialog.value = true
  } else {
    uni.showToast({
      title: `即将前往${type}认证`,
      icon: 'none',
    })
  }
}

// 关闭邀请码对话框
const closeInviteDialog = () => {
  showInviteDialog.value = false
  inviteCode.value = ''
}

// 提交邀请码
const submitInviteCode = async () => {
  if (!inviteCode.value) {
    uni.showToast({
      title: '请输入邀请码',
      icon: 'none',
    })
    return
  }

  // 这里可以添加邀请码验证和提交逻辑
  const res = await putUserAutenticationSponsor(inviteCode.value)
  // 关闭对话框
  closeInviteDialog()
  if (res.code === 200) {
    memberStore.profile!.user.status = 1
    memberStore.profile!.user.inviteCode = inviteCode.value
    uni.showToast({
      title: '认证成功',
      icon: 'success',
    })
  } else {
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })
  }
}

// 关闭学生认证对话框
const closeStudentDialog = () => {
  showStudentDialog.value = false
  studentForm.value = {
    schoolId: '',
    studentId: '',
  }
}

// 提交学生认证信息
const submitStudentForm = async () => {
  if (!studentForm.value.schoolId) {
    uni.showToast({
      title: '请选择学校',
      icon: 'none',
    })
    return
  }

  if (!studentForm.value.studentId) {
    uni.showToast({
      title: '请输入学号',
      icon: 'none',
    })
    return
  }
  console.log(studentForm.value)

  // 这里预留给后端发送认证请求的逻辑
  const res = await putUserAutenticationStudent(studentForm.value)

  if (res.code === 200) {
    // 更新用户认证状态
    memberStore.profile!.user.status = 1
    memberStore.profile!.user.schoolId = parseInt(studentForm.value.schoolId)
    memberStore.profile!.user.studentId = studentForm.value.studentId

    uni.showToast({
      title: '学生认证成功',
      icon: 'success',
    })
  } else {
    uni.showToast({
      title: res.msg || '认证失败，请重试',
      icon: 'none',
    })
  }

  // 关闭对话框
  closeStudentDialog()
}

// 身份证号码验证函数
const validateIdCard = (idCard: string): boolean => {
  // 清空错误信息
  idCardError.value = ''

  // 空值检查,如果为空则不验证
  if (!idCard) {
    return true
  }

  // 15位或18位验证
  const reg = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/
  if (!reg.test(idCard)) {
    idCardError.value = '身份证号格式不正确'
    return false
  }

  return true
}

// 定义性别变量，初始值为用户性别，如果未设置则为undefined
const selectedGender = ref<number | undefined>(userProfile.value?.gender)

// 性别选项
const genderOptions = [
  { text: '男', value: 1 },
  { text: '女', value: 2 },
]

// 性别文字展示
const getGenderText = (gender: number | undefined) => {
  if (gender === 1) return '男'
  if (gender === 2) return '女'
  return '未知'
}

// 处理性别变化
const handleGenderChange = (gender: number) => {
  selectedGender.value = gender
  // 用户可以自行实现性别变化后的处理逻辑
  console.log('性别已更改为:', getGenderText(gender))
}

// 判断性别按钮是否选中
const isGenderSelected = (gender: number) => {
  return selectedGender.value === gender
}

// 认证状态文字展示
const getStatusText = (status: number | undefined) => {
  if (status === 1) {
    return certificationType.value === 'sponsor' ? '赞助商认证' : '学生认证'
  }
  return '未认证'
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 处理确认按钮点击
const handleConfirm = async () => {
  if (!validateIdCard(editableIdCard.value)) {
    return
  }
  const res = await putUserAPI({
    userName: editableName.value,
    gender: selectedGender.value,
    idCard: editableIdCard.value,
  })
  if (res.code === 200) {
    memberStore.profile!.user.gender = selectedGender.value || 0
    memberStore.profile!.user.idCard = editableIdCard.value || ''
    memberStore.profile!.user.userName = editableName.value || ''
    uni.showToast({
      title: '修改成功',
      icon: 'success',
    })
    setTimeout(() => {
      goBack()
    }, 1000)
  } else {
    uni.showToast({
      title: res.msg,
      icon: 'none',
    })
  }
}

// 处理事件的类型定义
type PickerChangeEvent = {
  detail: {
    value: number
  }
}

// 组件挂载时获取学校列表
onMounted(() => {
  getSchoolList()
})
</script>

<template>
  <view class="profile-container">
    <!-- 顶部导航栏 -->
    <view class="header" :style="{ paddingTop: 'var(--status-bar-height, 25px)' }">
      <view class="header-content">
        <view class="back-btn" @tap="goBack">
          <text class="iconfont icon-arrow-left">←</text>
        </view>
        <view class="title">个人资料</view>
        <view class="right-space"></view>
      </view>
    </view>

    <!-- 用户资料卡片 -->
    <view class="profile-card">
      <!-- 头像 -->
      <view class="avatar-section">
        <image
          class="avatar"
          :src="userProfile?.image || '/static/images/not_login_avatar.png'"
          mode="aspectFill"
        ></image>
        <view class="user-id">ID: {{ userProfile?.id || '无' }}</view>
      </view>

      <!-- 基本信息 -->
      <view class="info-section">
        <!-- 可编辑的用户名 -->
        <view class="info-item">
          <text class="label">用户名</text>
          <input
            class="editable-input"
            v-model="editableName"
            placeholder="请输入用户名"
            :maxlength="20"
          />
        </view>

        <!-- 性别选择器 -->
        <view class="info-item">
          <text class="label">性别</text>
          <view class="gender-selector">
            <view
              v-for="option in genderOptions"
              :key="option.value"
              class="gender-option"
              :class="{ 'gender-selected': isGenderSelected(option.value) }"
              @tap="handleGenderChange(option.value)"
            >
              <view class="radio-btn">
                <view class="radio-inner" v-if="isGenderSelected(option.value)"></view>
              </view>
              <text>{{ option.text }}</text>
            </view>
          </view>
        </view>

        <view class="info-item">
          <text class="label">身份证号</text>
          <view class="input-wrapper">
            <input
              class="editable-input"
              v-model="editableIdCard"
              placeholder="请输入身份证号"
              :maxlength="18"
              type="idcard"
            />
            <text class="error-text" v-if="idCardError">{{ idCardError }}</text>
          </view>
        </view>

        <!-- 学校信息（仅当存在时显示） -->
        <view class="info-item" v-if="userProfile?.schoolId && userSchoolName">
          <text class="label">学校</text>
          <text class="value readonly">{{ userSchoolName }}</text>
        </view>

        <!-- 学号信息（仅当存在时显示） -->
        <view class="info-item" v-if="userProfile?.studentId">
          <text class="label">学号</text>
          <text class="value readonly">{{ userProfile.studentId }}</text>
        </view>

        <view class="info-item cert-status-item">
          <text class="label">认证状态</text>
          <view class="status-wrapper">
            <view
              class="value status"
              :class="{
                'status-verified': userProfile?.status === 1,
                'status-student': certificationType === 'student',
                'status-sponsor': certificationType === 'sponsor',
              }"
              @tap="handleStatusClick"
            >
              <text v-if="certificationType === 'student'" class="cert-icon">🎓</text>
              <text v-else-if="certificationType === 'sponsor'" class="cert-icon">🏆</text>
              <text class="status-text">{{ getStatusText(userProfile?.status) }}</text>
              <text class="arrow-icon" :class="{ 'arrow-up': showCertOptions }">{{
                showCertOptions ? '↑' : '↓'
              }}</text>
            </view>

            <!-- 认证选项 -->
            <view class="cert-options" v-if="showCertOptions">
              <view class="cert-option student" @tap="goCertification('学生')">
                <text class="cert-icon">🎓</text>
                <text class="cert-text">学生认证</text>
              </view>
              <view class="cert-option sponsor" @tap="goCertification('赞助商')">
                <text class="cert-icon">🏆</text>
                <text class="cert-text">赞助商认证</text>
              </view>
            </view>
          </view>
        </view>
        <view class="info-item">
          <text class="label">可取次数</text>
          <text class="value times">{{ userProfile?.availableTimes || 0 }}</text>
        </view>
      </view>
    </view>

    <!-- 确认按钮 -->
    <view class="confirm-btn-wrapper">
      <button class="confirm-btn" @tap="handleConfirm">确认</button>
    </view>

    <!-- 邀请码输入对话框 -->
    <view class="dialog-mask" v-if="showInviteDialog" @tap="closeInviteDialog"></view>
    <view class="invite-dialog" v-if="showInviteDialog">
      <view class="dialog-header">
        <text class="dialog-title">赞助商认证</text>
        <text class="dialog-close" @tap="closeInviteDialog">×</text>
      </view>
      <view class="dialog-content">
        <text class="dialog-tip">请输入赞助商邀请码</text>
        <input
          class="invite-input"
          v-model="inviteCode"
          placeholder="请输入邀请码"
          :maxlength="20"
        />
      </view>
      <view class="dialog-footer">
        <button class="dialog-btn cancel" @tap="closeInviteDialog">取消</button>
        <button class="dialog-btn confirm" @tap="submitInviteCode">确认</button>
      </view>
    </view>

    <!-- 学生认证对话框 -->
    <view class="dialog-mask" v-if="showStudentDialog" @tap="closeStudentDialog"></view>
    <view class="student-dialog" v-if="showStudentDialog">
      <view class="dialog-header">
        <text class="dialog-title">学生认证</text>
        <text class="dialog-close" @tap="closeStudentDialog">×</text>
      </view>
      <view class="dialog-content">
        <view class="form-item">
          <text class="form-label">选择学校</text>
          <picker
            class="school-picker"
            mode="selector"
            :range="schoolList"
            range-key="schoolName"
            @change="(e:UniHelper.SelectorPickerOnChangeEvent) => studentForm.schoolId = schoolList[e.detail.value].id.toString()"
          >
            <view class="picker-value">
              {{
                schoolList.find((school) => school.id.toString() === studentForm.schoolId)
                  ?.schoolName || '请选择学校'
              }}
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">学号</text>
          <input
            class="student-input"
            v-model="studentForm.studentId"
            placeholder="请输入学号"
            :maxlength="20"
          />
        </view>
      </view>
      <view class="dialog-footer">
        <button class="dialog-btn cancel" @tap="closeStudentDialog">取消</button>
        <button class="dialog-btn confirm" @tap="submitStudentForm">确认</button>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.profile-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-bottom: 40rpx;
}

// 顶部导航栏
.header {
  background: linear-gradient(125deg, #2c3e50, #4a69bd, #1e3c72);
  color: #fff;

  .header-content {
    height: 90rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;

    .back-btn {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .iconfont {
        font-size: 40rpx;
      }
    }

    .title {
      font-size: 34rpx;
      font-weight: 600;
    }

    .right-space {
      width: 60rpx;
    }
  }
}

// 用户资料卡片
.profile-card {
  margin: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;

  // 头像部分
  .avatar-section {
    padding: 40rpx;
    background: linear-gradient(to right, rgba(74, 105, 189, 0.1), rgba(44, 62, 80, 0.1));
    display: flex;
    flex-direction: column;
    align-items: center;

    .avatar {
      width: 160rpx;
      height: 160rpx;
      border-radius: 80rpx;
      border: 6rpx solid rgba(255, 255, 255, 0.8);
      box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
      margin-bottom: 20rpx;
    }

    .user-id {
      font-size: 26rpx;
      color: #666;
      background-color: rgba(255, 255, 255, 0.6);
      padding: 6rpx 20rpx;
      border-radius: 30rpx;
    }
  }

  // 信息部分
  .info-section {
    padding: 30rpx;

    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx 0;
      border-bottom: 1rpx solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .label {
        color: #666;
        font-size: 28rpx;
      }

      .value {
        color: #333;
        font-size: 28rpx;
        font-weight: 500;

        &.status {
          color: #ff6b6b;

          &.status-verified {
            color: #4a69bd;
          }
        }

        &.times {
          font-weight: 600;
          color: #4a69bd;
        }

        &.readonly {
          color: #4a69bd;
          padding: 0 20rpx;
          background-color: rgba(74, 105, 189, 0.05);
          border-radius: 6rpx;
          padding: 8rpx 16rpx;
        }
      }

      // 可编辑的输入框样式
      .editable-input {
        flex: 1;
        text-align: right;
        height: 60rpx;
        font-size: 28rpx;
        color: #333;
        padding: 0 20rpx;
        max-width: 400rpx;
        background-color: #f9f9f9;
        border-radius: 6rpx;
      }

      .input-wrapper {
        display: flex;
        flex-direction: column;
        align-items: flex-end;

        .error-text {
          font-size: 22rpx;
          color: #ff4d4f;
          margin-top: 4rpx;
        }
      }

      // 性别选择器样式
      .gender-selector {
        display: flex;

        .gender-option {
          display: flex;
          align-items: center;
          margin-left: 30rpx;

          &:first-child {
            margin-left: 0;
          }

          .radio-btn {
            width: 36rpx;
            height: 36rpx;
            border-radius: 50%;
            border: 2rpx solid #ccc;
            margin-right: 10rpx;
            display: flex;
            align-items: center;
            justify-content: center;

            .radio-inner {
              width: 20rpx;
              height: 20rpx;
              border-radius: 50%;
              background-color: #4a69bd;
            }
          }

          &.gender-selected {
            .radio-btn {
              border-color: #4a69bd;
            }

            text {
              color: #4a69bd;
              font-weight: 500;
            }
          }
        }
      }

      // 认证状态相关样式
      &.cert-status-item {
        position: relative;

        .status-wrapper {
          display: flex;
          flex-direction: column;
          align-items: flex-end;

          .status {
            display: flex;
            align-items: center;
            background-color: rgba(0, 0, 0, 0.05);
            padding: 8rpx 16rpx;
            border-radius: 6rpx;

            .cert-icon {
              margin-right: 8rpx;
              font-size: 28rpx;
            }

            .status-text {
              color: #333;
              font-size: 28rpx;
            }

            .arrow-icon {
              margin-left: 10rpx;
              font-size: 24rpx;
              transition: transform 0.3s;

              &.arrow-up {
                transform: rotate(180deg);
              }
            }

            &.status-student {
              background-color: rgba(82, 196, 26, 0.1);
            }

            &.status-sponsor {
              background-color: rgba(250, 173, 20, 0.1);
            }
          }

          .cert-options {
            margin-top: 16rpx;
            background-color: #fff;
            border-radius: 10rpx;
            box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
            width: 100%;
            overflow: hidden;
            animation: slideDown 0.3s ease;

            .cert-option {
              display: flex;
              align-items: center;
              padding: 16rpx 20rpx;
              border-bottom: 1rpx solid #f5f5f5;

              &:last-child {
                border-bottom: none;
              }

              .cert-icon {
                margin-right: 16rpx;
                font-size: 32rpx;
              }

              .cert-text {
                font-size: 26rpx;
                color: #333;
              }

              &:active {
                background-color: #f9f9f9;
              }

              &.student {
                color: #4a69bd;
              }

              &.sponsor {
                color: #e74c3c;
              }
            }
          }
        }
      }
    }
  }
}

// 确认按钮样式
.confirm-btn-wrapper {
  padding: 20rpx 30rpx 50rpx;

  .confirm-btn {
    background: linear-gradient(to right, #4a69bd, #1e3c72);
    color: #fff;
    border-radius: 45rpx;
    font-size: 32rpx;
    height: 90rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border: none;
    box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);

    &:active {
      opacity: 0.9;
      transform: translateY(2rpx);
    }
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 邀请码对话框样式
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 100;
}

.invite-dialog,
.student-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  z-index: 101;
  animation: dialogFadeIn 0.3s ease;

  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f5f5f5;

    .dialog-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }

    .dialog-close {
      font-size: 40rpx;
      color: #999;
      padding: 0 10rpx;
    }
  }

  .dialog-content {
    padding: 30rpx;

    .dialog-tip {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 20rpx;
      display: block;
    }

    .invite-input,
    .student-input {
      width: 100%;
      height: 80rpx;
      border: 1rpx solid #e0e0e0;
      border-radius: 8rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      box-sizing: border-box;
    }

    .form-item {
      margin-bottom: 24rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .form-label {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 12rpx;
        display: block;
      }

      .school-picker {
        width: 100%;
        height: 80rpx;
        border: 1rpx solid #e0e0e0;
        border-radius: 8rpx;
        overflow: hidden;

        .picker-value {
          height: 80rpx;
          line-height: 80rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          color: #333;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .picker-arrow {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    border-top: 1rpx solid #f5f5f5;

    .dialog-btn {
      flex: 1;
      height: 90rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30rpx;
      border: none;
      background-color: transparent;

      &.cancel {
        color: #666;
        border-right: 1rpx solid #f5f5f5;
      }

      &.confirm {
        color: #4a69bd;
        font-weight: 500;
      }

      &:active {
        background-color: #f9f9f9;
      }
    }
  }
}

@keyframes dialogFadeIn {
  from {
    opacity: 0;
    transform: translate(-50%, -60%);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
}
</style>
